package com.example.customer;

import com.example.client.FraudService;
import com.example.client.FraudReviewResponse;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;

@Service
public class CustomerService {

    private final CustomerRepository customerRepository;
    private final FraudService fraudService;

    @Autowired
    public CustomerService(CustomerRepository customerRepository, FraudService fraudService) {
        this.customerRepository = customerRepository;
        this.fraudService = fraudService;
    }

    public String registerCustomer(CustomerRegistryRequest request) {
        System.out.println("=== 开始用户注册流程 ===");
        System.out.println("请求数据: " + request.name() + ", " + request.email());

        // 创建Customer对象
        Customer customer = new Customer(request.name(), request.email());

        // 检查email是否已经注册
        Optional<Customer> existEmail = customerRepository.findByEmail(customer.getEmail());
        System.out.println("邮箱重复检查: " + (existEmail.isPresent() ? "重复" : "不重复"));
        if (existEmail.isPresent()) {
            System.out.println("注册失败: 邮箱已存在 " + customer.getEmail());
            throw new RuntimeException("Email地址已经注册");
        }

        // 调用fraud服务检查征信
        System.out.println("准备调用Fraud服务...");
        try {
            FraudReviewResponse fraudReviewResponse = fraudService.isFraudster(customer.getEmail());
            System.out.println("Fraud服务返回结果: " + fraudReviewResponse.isFraudster());

            if (fraudReviewResponse.isFraudster()) {
                System.out.println("注册失败: 用户存在征信问题 " + customer.getEmail());
                throw new RuntimeException("用户存在征信问题");
            } else {
                System.out.println("征信检查通过");
            }
        } catch (Exception e) {
            System.out.println("调用Fraud服务异常: " + e.getMessage());
            throw new RuntimeException("征信检查服务暂时不可用");
        }

        // 保存到数据库
        customerRepository.save(customer);
        System.out.println("注册成功: " + customer);
        System.out.println("=== 用户注册完成 ===\n");
        return "注册成功";
    }
}